class Solution:
    def spiralOrder(self, matrix):
        self.i, self.j = 0, 0
        self.dir_flag = "you"
        self.res_list = []
        len_all = len(matrix) * len(matrix[0])
        while len(self.res_list) < len_all:
            if self.dir_flag == "you":
                self.you(matrix)
            elif self.dir_flag == "xia":
                self.xia(matrix)
            elif self.dir_flag == "zuo":
                self.zuo(matrix)
            elif self.dir_flag == "shang":
                self.shang(matrix)
        return self.res_list

    def you(self, matrix):
        try:
            self.res_list.append(matrix[self.i].pop(self.j))
        except:
            self.j = -1
            self.i += 1
            self.dir_flag = "xia"

    def xia(self, matrix):
        try:
            self.res_list.append(matrix[self.i].pop(self.j))
            self.i += 1
        except:
            self.i -= 1
            self.dir_flag = "zuo"

    def zuo(self, matrix):
        try:
            self.res_list.append(matrix[self.i].pop(self.j))
        except:
            self.j = 0
            self.i -= 1
            self.dir_flag = "shang"

    def shang(self, matrix):
        try:
            self.res_list.append(matrix[self.i].pop(self.j))
            self.i -= 1
        except:
            self.i += 1
            self.dir_flag = "you"


a = Solution()
print(a.spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]))